package com.x.uikit.router;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Looper;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;

import com.x.uikit.UIKitImpl;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class XRouteManager {
    public static final String ROUTER_ACTION = "com.x.uikit.xrouter.XRouterCenter.ACTION";
    private final List<IXRouteHandler> mRouteHandlers = new CopyOnWriteArrayList<>();
    private final Handler mMainHandler = new Handler(Looper.getMainLooper());


    public XRouteManager(@NonNull Context context) {
        IntentFilter filter = new IntentFilter();
        filter.addAction(ROUTER_ACTION);
        context.registerReceiver(new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (ROUTER_ACTION.equals(intent.getAction())) {
                    XRoute route = UIKitImpl.getRoute(intent);
                    if (route != null) {
                        navigate(route);
                    }
                }

            }
        }, filter);
    }


    @MainThread
    public void registerRouteHandler(IXRouteHandler handler) {
        if (handler == null) {
            return;
        }
        mRouteHandlers.add(handler);
    }

    @MainThread
    public void unregisterRouteHandler(IXRouteHandler handler) {
        if (handler == null) {
            return;
        }
        mRouteHandlers.remove(handler);
    }

    private void runInMainThread(Runnable runnable) {
        if (runnable == null) {
            return;
        }
        if (Looper.myLooper() == Looper.getMainLooper()) {
            runnable.run();
        } else {
            mMainHandler.post(runnable);
        }
    }

    protected void navigate(@NonNull XRoute route) {
        mMainHandler.post(new Runnable() {
            @Override
            public void run() {
                navigateInner(route);
            }
        });
    }

    protected void navigateInner(@NonNull XRoute route) {
        for (IXRouteHandler handler : mRouteHandlers) {
            if (handler.needIntercept(route)) {
                handler.onHandle(route);
                return;
            }
        }

    }


}
